from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.user import User
from app.schemas.user import User as UserSchema, UserCreate, UserUpdate, UserList
from app.services.user_service import UserService
from app.api.deps import get_current_active_user, get_current_superuser
from app.api.dependencies import get_user_service

router = APIRouter(prefix="/users", tags=["users"])

@router.get("/", response_model=UserList)
async def get_users(
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100),
    search: Optional[str] = Query(None),
    is_active: Optional[bool] = Query(None),
    user_service: UserService = Depends(get_user_service),
    current_user: User = Depends(get_current_superuser)
):
    """获取用户列表（仅超级管理员）"""
    users, total = user_service.get_users(skip=skip, limit=limit, search=search, is_active=is_active)
    return UserList(items=users, total=total, page=skip//limit+1, size=limit)

@router.get("/me", response_model=UserSchema)
async def get_current_user(
    current_user: User = Depends(get_current_active_user),
    user_service: UserService = Depends(get_user_service)
):
    """获取当前用户信息"""
    # 安全地转换ID为整数
    user_id = int(str(current_user.id))
    user_with_completion = user_service.get_user(user_id)
    return user_with_completion

@router.get("/{user_id}", response_model=UserSchema)
async def get_user(
    user_id: int,
    user_service: UserService = Depends(get_user_service),
    current_user: User = Depends(get_current_superuser)
):
    """获取指定用户信息（仅超级管理员）"""
    user = user_service.get_user(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

@router.post("/", response_model=UserSchema)
async def create_user(
    user_create: UserCreate,
    user_service: UserService = Depends(get_user_service),
    current_user: User = Depends(get_current_superuser)
):
    """创建新用户（仅超级管理员）"""
    return user_service.create_user(user_create)

@router.put("/{user_id}", response_model=UserSchema)
async def update_user(
    user_id: int,
    user_update: UserUpdate,
    user_service: UserService = Depends(get_user_service),
    current_user: User = Depends(get_current_superuser)
):
    """更新用户信息（仅超级管理员）"""
    user = user_service.update_user(user_id, user_update)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

@router.delete("/{user_id}")
async def delete_user(
    user_id: int,
    user_service: UserService = Depends(get_user_service),
    current_user: User = Depends(get_current_superuser)
):
    """删除用户（仅超级管理员）"""
    if not user_service.delete_user(user_id):
        raise HTTPException(status_code=404, detail="用户不存在")
    return {"message": "用户删除成功"}

@router.patch("/{user_id}/activate")
async def activate_user(
    user_id: int,
    user_service: UserService = Depends(get_user_service),
    current_user: User = Depends(get_current_superuser)
):
    """激活用户（仅超级管理员）"""
    user = user_service.activate_user(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return {"message": "用户激活成功", "user": user}

@router.patch("/{user_id}/deactivate")
async def deactivate_user(
    user_id: int,
    user_service: UserService = Depends(get_user_service),
    current_user: User = Depends(get_current_superuser)
):
    """停用用户（仅超级管理员）"""
    user = user_service.deactivate_user(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return {"message": "用户停用成功", "user": user}